/*
 * Copyright 2021 TiKV Project Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.webank.tikv.region;

import com.google.common.base.Strings;
import com.webank.tikv.kvproto.Metapb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReplicaSelector {

    private final String zone;

    public ReplicaSelector(String zone) {
        this.zone = zone;
    }

    public List<Metapb.Peer> select(Metapb.Peer leader, List<Metapb.Peer> peers, List<TiStore> stores) {
        List<Metapb.Peer> result = new ArrayList<>(peers.size());

        Map<Long, String> storeZoneMap = new HashMap<>();
        for (TiStore store : stores) {
            storeZoneMap.put(store.getId(), store.getZone());
        }

        for (Metapb.Peer peer : peers) {
            String storeZone = storeZoneMap.get(peer.getStoreId());
            Metapb.PeerRole role = peer.getRole();
            if (role == Metapb.PeerRole.Voter && (Strings.isNullOrEmpty(zone) || zone.equals(storeZone))) {
                result.add(peer);
            }
        }

        if (result.isEmpty()) {
            result.add(leader);
        }
        return result;
    }
}
